'use strict';

var config = require('../../config/environment');

var _ = require('lodash');
var moment = require('moment');

var formatDate = function(jsonResult, names) {
    jsonResult = JSON.stringify(jsonResult);
    _.map(names, function(name, index) {
        var reg = new RegExp('"' + name + '":\s*"[^\"]*"', "ig");
        jsonResult = jsonResult.replace(reg, function(item) {
            var newItem = JSON.parse("{" + item + "}");
            var itemValue = _.values(newItem)[0];
            var parseItemValue = _.toNumber(itemValue) ? parseInt(itemValue) : itemValue;
            var formatTime = moment(parseItemValue).format('YYYY-MM-DD HH:mm:ss');
            // var formatTime = moment(_.values(newItem)[0])._d.getTime();
            return '"' + name + '":"' + formatTime + '"';
        });
    });
    return JSON.parse(jsonResult);
};

exports.formatResult = function(err, data, res) {
    if (err) {
        var status = err.status ? err.status : 500;
        return res.status(status).json({
            isSuccess: false,
            code: err.code ? err.code : '0x0001',
            error: err.message ? err.message : err,
            data: data
        });
    } else {
        data = formatDate(data, ['createdAt', 'updatedAt', 'deletedAt', 'startDate', 'endDate', 'created_at', 'promote_at', 'updated_at', 'started_at'])
        res.json({
            isSuccess: true,
            code: "0x0001",
            data: data
        });
    }
}

/**
 * [get ]
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
exports.getKueFromQueue = function(obj) {
    var pending = 0,
        res = {},
        callback, done;

    return function _(arg) {
        switch (typeof arg) {
            case 'function':
                callback = arg;
                break;
            case 'string':
                ++pending;
                obj[arg](function(err, val) {
                    if (done) return;
                    if (err) return done = true, callback(err);
                    res[arg] = val;
                    --pending || callback(null, res);
                });
                break;
        }
        return _;
    };
}